<template>
	<view>
		<view>分片上传模拟</view>
		<button type="default" @click="choosefile()">选择文件</button>
	</view>
</template>

<script>
	import sparkmd5 from './spark-md5-js/sprak-md5 - 3.0.2.js';
	export default {
		data() {
			return {
				fileuploadgroup:{},
				uploaditem:[]
			}
		},
		methods: {
			getfilemd5:function(file,tempfilepath){
				var self = this;
				function Togetfiles(files,tempfilepaths) {
					/* 
						{
							files
							filename
							itemid
							filesp_group
							md5val
							times
						}
					 */
					this.files = files
					// this.filepath = tempfilepaths
					this.filename = ''//文件名
					this.itemid = ''//文件队列的itemid
					this.filesp_group = []//md5验证生成之前的碎片数组
					this.md5val = ''//储存md5验证值
					this.times = new Date().getFullYear()+'_'+new Date().getMonth()+'_'+new Date().getDate()+'_'+new Date().getHours()+'_'+new Date().getMinutes()+'_'+new Date().getSeconds()+'_'+new Date().getMilliseconds()//时间拼接
				}
				Togetfiles.prototype.fn = function() {
					/* 
						fileuploadgroup:{
							'file_'+fnself.times:{
								fns
								ifupload
							}
						}
					 */
					var fnself = this;
					self.fileuploadgroup['file_'+fnself.times] = {
						fns:fnself,
						ifupload : 1,//1为允许上传
					}
					/* 
						[{
							itemid
							filename
							times
							
						}]
					 */
					var flag = 0
					for(var i=0;i<self.uploaditem.length;i++){
						if(self.uploaditem[i].itemid == 'file_'+fnself.times) {
							flag = 1
						}
					}
					if(flag == 0){
						self.uploaditem.push({
							itemid:'file_'+fnself.times,
							filename:fnself.files.name,
							times:fnself.times,
							hadupload:'0%',
							total:'0%'
						})
					}
					//获取hash
					//var reader = new FileReader();reader.readAsBinaryString(this.files);/* 读取文件 */reader.onload = function(e) {fnself.md5val = sparkmd5.hashBinary(e.target.result)/*获得文件MD5*/};
					let spark = new sparkmd5.ArrayBuffer();
					spark.append(this.files);
					fnself.md5val = spark.end(false);
				}
				new Togetfiles(file,tempfilepath).fn()
			},
			choosefile: function() {
				var _this = this;
				if(document){
					uni.chooseFile({
						success:function(res){
							var tempfile = res.tempFiles[0];
							_this.getfilemd5(tempfile)
						}
					})
				}else{
					//TODO handle the exception
					if(wx.chooseMessageFile){
						wx.chooseMessageFile({
							success:function(res) {
								var tempfile = res.tempFiles[0];
								_this.getfilemd5(tempfile)
							}
						})
					}
				}
			}
		}
	}
</script>

<style>
</style>
